package com.jiaomatech.tencent.cos.endpoint;

import com.qcloud.cos.COSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.context.ApplicationContext;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 监控cos应用服务的运行状况.
 *
 * @author jm
 */
@Endpoint(id = "com/jiaomatech/tencent/cos")
public class CosEndpoint {

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 返回监控的内容.
     *
     * @return
     */
    @ReadOperation
    public Map<String, Object> invoke() {
        Map<String, Object> result = new HashMap<>();

        Map<String, COSClient> cosClientMap = applicationContext
            .getBeansOfType(COSClient.class);

        int size = cosClientMap.size();

        List<Object> cosClientList = new ArrayList<>();

        cosClientMap.keySet().forEach(beanName -> {
            Map<String, Object> cosProperties = new HashMap<>();
            COSClient client = cosClientMap.get(beanName);
            cosProperties.put("beanName", beanName);
            cosProperties.put("clientConfiguration", client.getClientConfig());
            cosProperties.put("bucketList", client.listBuckets().stream()
                .map(bucket -> bucket.getName()).toArray());
            cosClientList.add(cosProperties);
        });

        result.put("size", size);
        result.put("info", cosClientList);

        return result;
    }

}
